package com.likou;

import java.util.HashMap;
import java.util.Map;

/**
 * Author: 陈桂明
 * Date: 2025/3/28 下午5:00
 * Description: q1
 */
public class q1 {
    // // 哈希表
    // public int[] twoSum(int[] nums, int target) {
    //     Map<Integer, Integer> hashtable = new HashMap<Integer, Integer>();
    //     for (int i = 0; i < nums.length; ++i) {
    //         if (hashtable.containsKey(target - nums[i])) {
    //             return new int[]{hashtable.get(target - nums[i]), i};
    //         }
    //         hashtable.put(nums[i], i);
    //     }
    //     return new int[0];
    // }

    public int[] twoSum(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        HashMap<Integer, Integer> map = new HashMap<>(right);
        while (left <= right) {
            if (map.containsKey(target - nums[left])) {
                return new int[]{map.get(target - nums[left]), left};
            }
            map.put(nums[left], left);

            if (map.containsKey(target - nums[right])) {
                return new int[]{map.get(target - nums[right]), right};
            }
            map.put(nums[right], right);

            right--;
            left++;
        }
        return null;
    }
}
